package com.ChengXiZi.service.impl;

import com.ChengXiZi.constant.MessageConstant;
import com.ChengXiZi.dto.UserCommunityAddDTO;
import com.ChengXiZi.entity.UserCommunity;
import com.ChengXiZi.exception.RepeatJoinException;
import com.ChengXiZi.mapper.UserCommunityMapper;
import com.ChengXiZi.service.UserCommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserCommunityServiceImpl implements UserCommunityService {

    @Autowired
    private UserCommunityMapper userCommunityMapper;

    /**
     * 用户加入社区
     * @param userCommunityAddDTO
     * @return
     */
    @Override
    public void join(UserCommunityAddDTO userCommunityAddDTO) {

        //查询是否关注过目标社区
        UserCommunity userCommunity = userCommunityMapper.selectByDto(userCommunityAddDTO);
        if (userCommunity != null) {
            //关注过报重复加入异常
            throw new RepeatJoinException(MessageConstant.REPEAT_JOIN);
        }

        //构造用户社区关系对象
        userCommunity = UserCommunity.builder()
                .userId(userCommunityAddDTO.getUserId())
                .communityId(userCommunityAddDTO.getCommunityId())
                .role(0)
                .joinTime(LocalDateTime.now())
                .status(1)
                .build();
        //向用户关系表内添加新记录
        userCommunityMapper.insert(userCommunity);
    }
}
